from werkzeug.security import generate_password_hash, check_password_hash
from flask_jwt_extended import create_access_token
from app.models.user import User
from app import db

class AuthService:
    def register(self, data):
        if User.query.filter_by(username=data['username']).first():
            return {'error': '用户名已存在'}, 400
        
        if User.query.filter_by(email=data['email']).first():
            return {'error': '邮箱已存在'}, 400
        
        user = User(
            username=data['username'],
            email=data['email'],
            password_hash=generate_password_hash(data['password'])
        )
        
        db.session.add(user)
        db.session.commit()
        
        return {'message': '注册成功'}, 201
    
    def login(self, data):
        user = User.query.filter_by(username=data['username']).first()
        
        if not user or not check_password_hash(user.password_hash, data['password']):
            return {'error': '用户名或密码错误'}, 401
        
        access_token = create_access_token(identity=user.id)
        return {'access_token': access_token}, 200 